package com.study.lihan.io;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;

/**
 * @Author: lihan
 * @Date : 2022/1/10- 01
 * @DESCRIPTION: com.study.lihan.io
 * @version: 1.0
 */
public class NIO {
    public static void main(String[] args)  throws Exception{
        LinkedList<SocketChannel> clients = new LinkedList<>();

        ServerSocketChannel ss = ServerSocketChannel.open();//服务端开启监听，接受客户端
        ss.bind(new InetSocketAddress(9090));
        ss.configureBlocking(false);//只让客户端不阻塞

         while (true){
             Thread.sleep(1000);
             SocketChannel client = ss.accept(); // 不会阻塞，返回 -1，null
             //accept调用了内核，在BIO的时候，一直卡着，在NIO，不卡着，返回-1， null
             //如果客户端连接，accept返回的是这个客户端的fd，

             if(client == null){
                 System.out.println("null");
             }else{
                 //socket（服务端的listen socket连接请求三次握手后）
                 client.configureBlocking(false);
                 int port = client.socket().getPort();
                 System.out.println("client port:"+port);
                 clients.add(client);
             }

             ByteBuffer buffer = ByteBuffer.allocateDirect(4096);//可以在堆里或者堆外
             //遍历已经连接进来的客户端能不能读写数据
             for(SocketChannel c : clients){
                 int num = c.read(buffer); // >0 -1 ,不会阻塞
                 if(num >0){
                     buffer.flip();
                     byte[] aaa = new byte[buffer.limit()];
                     buffer.get(aaa);

                     String b = new String(aaa);
                     System.out.println(c.socket().getPort() + ":" + b);
                     buffer.clear();
                 }
             }
         }


    }
}
